package top.tungsword.webconsole.globalerror;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import top.tungsword.webconsole.biz.response.WebReturnInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chenji.yu
 * @date 2020/4/21 10:28
 * @description
 * 统一异常处理
 */
@Component
public class WebExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                         Object handler, Exception e) {
        ModelAndView mv = new ModelAndView();

        //返回json数据
        HandlerMethod method = (HandlerMethod)handler;
        ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
        if(responseBody != null){
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            MappingJackson2JsonView view = new MappingJackson2JsonView();
            mv.setView(view);
            WebReturnInfo<String> webReturnInfo = WebReturnInfo.FAIL;
            webReturnInfo.setMessage("系统错误");

            //TODO 错误信息提示
            mv.addObject("data", webReturnInfo);
            return mv;
        }

        WebReturnInfo<String> webReturnInfo = WebReturnInfo.FAIL;
        webReturnInfo.setMessage("异常信息");
        mv.addObject("errorInfo", webReturnInfo);
        mv.setViewName("/error");
        //返回画面

        return mv;
    }
}
